<template>
  <view class="address-list-page">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="page-title">选择收货地址</text>
    </view>
    <view class="address-list">
      <view v-for="addr in addressList" :key="addr.id" class="address-item" :class="{selected: selected && selected.id === addr.id}">
        <view class="address-main" @click="selectAddress(addr)">
          <text class="address-name">{{ addr.name }}</text>
          <text class="address-phone">{{ addr.phone }}</text>
        </view>
        <view class="address-detail" @click="selectAddress(addr)">{{ addr.province }}{{ addr.city }}{{ addr.district }}{{ addr.detail }}</view>
        <view v-if="addr.isDefault" class="address-default">默认</view>
        <view class="address-actions">
          <button class="edit-btn" size="mini" @click.stop="editAddr(addr)">编辑</button>
          <button class="delete-btn" size="mini" @click.stop="deleteAddr(addr)">删除</button>
        </view>
      </view>
    </view>
    <button class="add-btn" @click="addAddr">+ 新增地址</button>
    <button class="confirm-btn" @click="confirmSelect">确定</button>
  </view>
</template>

<script>
import { getUserAddress, deleteAddress } from '@/api/address'
import { editOrderAddress } from '@/api/order'
export default {
  data() {
    return {
      addressList: [],
      selected: null
    }
  },
  onLoad() {
    this.loadList();
    // 监听编辑页事件通道，刷新列表
    const eventChannel = this.getOpenerEventChannel && this.getOpenerEventChannel();
    if (eventChannel) {
      eventChannel.on && eventChannel.on('addressChanged', () => {
        this.loadList();
      });
    }
  },
  methods: {
    loadList() {
      const userId = this.$store.state.user.id || uni.getStorageSync('userId');
      if (!userId) {
        uni.showToast({ title: '请先登录', icon: 'none' });
        return;
      }
      
      getUserAddress(userId).then(res => {
        if (res.code === 200 && res.data) {
          this.addressList = res.data;
          // 默认选中默认地址
          const def = res.data.find(a => a.isDefault);
          if (def) this.selected = def;
        }
      }).catch(err => {
        console.error('获取地址列表失败:', err);
        uni.showToast({ title: '获取地址列表失败', icon: 'none' });
      });
    },
    selectAddress(addr) {
      this.selected = addr;
    },
    confirmSelect() {
      if (!this.selected) {
        uni.showToast({ title: '请选择地址', icon: 'none' });
        return;
      }
      
      // 检查是否来自订单详情页面
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];
      
      if (prevPage && prevPage.route.includes('order/detail')) {
        // 来自订单详情页面，调用API修改订单地址
        const orderAddressData = {
          id: this.getOrderIdFromUrl(), // 从URL参数获取订单ID
          consigneeName: this.selected.name,
          consigneePhone: this.selected.phone,
          consigneeProvince: this.selected.province,
          consigneeCity: this.selected.city,
          consigneeRegion: this.selected.district,
          consigneeStreet: '',
          consigneeDetail: this.selected.detail
        };
        
        console.log('修改订单地址，提交数据:', orderAddressData);
        
        // 调用订单地址更新API
        editOrderAddress(orderAddressData).then(res => {
          if (res.code === 200) {
            uni.showToast({ title: '地址修改成功', icon: 'success' });
            setTimeout(() => {
              // 通知订单详情页面刷新数据
              const pages = getCurrentPages();
              const prevPage = pages[pages.length - 2];
              if (prevPage && prevPage.route.includes('order/detail')) {
                // 调用订单详情页面的刷新方法
                if (prevPage.refreshOrderData) {
                  prevPage.refreshOrderData();
                }
              }
              uni.navigateBack();
            }, 600);
          } else {
            uni.showToast({ title: res.msg || '地址修改失败', icon: 'none' });
          }
        }).catch(error => {
          console.error('修改订单地址失败:', error);
          uni.showToast({ title: '地址修改失败', icon: 'none' });
        });
      } else {
        // 原有的逻辑
        const eventChannel = this.getOpenerEventChannel();
        eventChannel.emit('addressSelected', this.selected);
        if (pages.length <= 1) {
          uni.reLaunch({ url: '/pages/order/submit' });
        } else {
          uni.navigateBack();
        }
      }
    },
    addAddr() {
      uni.navigateTo({ url: '/pages/address/edit' });
    },
    editAddr(addr) {
      uni.navigateTo({ url: `/pages/address/edit?id=${addr.id}&data=${encodeURIComponent(JSON.stringify(addr))}` });
    },
    deleteAddr(addr) {
      uni.showModal({
        title: '提示',
        content: '确定要删除该地址吗？',
        success: (res) => {
          if (res.confirm) {
            deleteAddress(addr.id).then(r => {
              if (r.code === 200) {
                uni.showToast({ title: '删除成功', icon: 'success' });
                this.loadList();
              } else {
                uni.showToast({ title: r.msg || '删除失败', icon: 'none' });
              }
            });
          }
        }
      });
    },
    
    // 从URL参数获取订单ID
    getOrderIdFromUrl() {
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      const options = currentPage.options;
      return options.orderId || null;
    }
  }
}
</script>

<style scoped>
.address-list-page { background: #fafafa; min-height: 100vh; padding-bottom: 120rpx; }
.page-header { background: #fff; padding: 24rpx; text-align: center; border-bottom: 1rpx solid #eee; }
.page-title { font-size: 36rpx; font-weight: bold; color: #333; }
.address-list { margin: 24rpx; }
.address-item { background: #fff; border-radius: 12rpx; margin-bottom: 18rpx; padding: 24rpx; border: 2rpx solid #eee; position: relative; }
.address-item.selected { border-color: #ff5000; box-shadow: 0 2rpx 12rpx #ffe5d0; }
.address-main { font-size: 32rpx; font-weight: bold; margin-bottom: 8rpx; }
.address-phone { margin-left: 32rpx; }
.address-detail { color: #666; font-size: 26rpx; margin-bottom: 8rpx; }
.address-default { display: inline-block; background: #ff9000; color: #fff; font-size: 22rpx; border-radius: 8rpx; padding: 2rpx 12rpx; margin-left: 12rpx; }
.address-actions { position: absolute; right: 24rpx; top: 24rpx; display: flex; gap: 12rpx; }
.edit-btn { background: #fff7e6; color: #ff9000; border: 1rpx solid #ff9000; border-radius: 8rpx; font-size: 24rpx; padding: 4rpx 18rpx; }
.delete-btn { background: #fff0f0; color: #ff4d4f; border: 1rpx solid #ff4d4f; border-radius: 8rpx; font-size: 24rpx; padding: 4rpx 18rpx; }
.add-btn { width: 90%; margin: 32rpx 5% 0 5%; background: #fff; color: #ff5000; font-size: 32rpx; border-radius: 32rpx; border: 2rpx solid #ff5000; }
.confirm-btn { width: 90%; margin: 32rpx 5%; background: linear-gradient(90deg, #ff5000, #ff9000); color: #fff; font-size: 32rpx; border-radius: 32rpx; }
</style> 